package edu.hunau.cxb19.oop.class20;

import java.util.HashMap;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;

/**
 *
 * @author hb
 *
 *         2020-03-23 15:34:03
 */
public class MapTest {

	@Test
	public void hashMapTest() {
		Map<Integer, String> maps = new HashMap<>();
		maps.put(1001, "haoren01");
		maps.put(1003, "haoren03");
		maps.put(1001, "haoren04");
		maps.put(1002, "haoren02");

		Set<Entry<Integer, String>> entrySet = maps.entrySet();
		for (Entry<Integer, String> entry : entrySet) {
			System.out.println(entry.getKey() + " : " + entry.getValue());
		}

		Set<Integer> keySet = maps.keySet();
		for (Integer key : keySet) {
			System.out.println(key + ":" + maps.get(key));
		}

		System.out.println(maps.size());
		System.out.println(maps);// {1001=haoren04, 1002=haoren02, 1003=haoren03}
		System.out.println(maps.containsKey(1001));// 默认调用对象的equals方法
		System.out.println(maps.containsValue("haoren02"));
		System.out.println(maps.get(1001));
	}

	@Test
	public void counterTest() {
		Map<Character, Integer> datas = counter("2342341112311131");
		System.out.println(datas);
	}

	/**
	 * 统计字符串中字符出现的次数
	 * 
	 * @param datas
	 * @return
	 */
	public Map<Character, Integer> counter(String datas) {
		Map<Character, Integer> maps = new HashMap<>();
		for (int i = 0; i < datas.length(); i++) {
			char c = datas.charAt(i);
			// 判定map中作为key的c是否出现过
			/*
			 * if (maps.containsKey(c)) { maps.put(c, maps.get(c) + 1); } else { maps.put(c,
			 * 1); }
			 */
			Integer counter = maps.get(c);
			counter = counter == null ? 1 : counter + 1;
			maps.put(c, counter);
		}
		return maps;
	}
}
